package com.bookmngsys.dto;

import com.bookmngsys.entity.BorrowHistory;
import com.bookmngsys.utils.CommonUtils;
import lombok.Data;

import javax.persistence.Id;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@Data
public class BorrowHistoryDTO{
    //书的的isbn
    private String isbn;
    //书的bookId
    private Integer bookId;
    //借书用户id
    private Integer readerId;
    //结束日期
    private Long borrowDate;
    //归还日期
    private Long returnDate;
    //是否归还
    private Boolean isReturned;
    @Id
    private Integer id;
    //实际还书日期，默认为null
    private Long realReturnDate;
    private Float fineAmount;
    public BorrowHistoryDTO(BorrowHistory borrowHistory) throws NoSuchFieldException, IllegalAccessException {
        Field[] fields = borrowHistory.getClass().getDeclaredFields();
        for(Field x: fields){
            x.setAccessible(true);
            Field y = BorrowHistoryDTO.class.getDeclaredField(x.getName());
            y.setAccessible(true);
            y.set(this, x.get(borrowHistory));
        }
        fineAmount = CommonUtils.getFineAmount(getReturnDate());
    }

    public static BorrowHistoryDTO entityChangeToDTO(BorrowHistory borrowHistory){
        try{
            return new BorrowHistoryDTO(borrowHistory);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
    public static List<BorrowHistoryDTO> entityChangeToDTO(List<BorrowHistory> borrowHistorys){
        List<BorrowHistoryDTO> ans = new ArrayList<>();
        BorrowHistoryDTO borrowHistoryDTO;
        for(BorrowHistory borrowHistory:borrowHistorys){
            borrowHistoryDTO = entityChangeToDTO(borrowHistory);
            if(borrowHistoryDTO != null){
                ans.add(borrowHistoryDTO);
            }
        }
        return ans;
    }
}
